$(function() {
    function homePageEvents()
    {
        // HOME PAGE SLIDE SHOW
        // Caching elements that need to be queried multiple times
        
        var homeSlideshowWrap = $('#slide-box');
        var homeSlidesContainer = homeSlideshowWrap.find('#slide');
        var homeSlides = homeSlidesContainer.children('div');

        var pager = homeSlideshowWrap.find('div.slideshow-progress-bar-wrap div.slideshow-progress-bar');
        var highlightBar = homeSlideshowWrap.find('div.highlight-bar');

        var pagerMarkup = new Array();
        var pagerElPercentW = 1 / homeSlides.length * 100;

        homeSlides.each(function(i) {
            // Make a pager element for each slide
            var oneBasedIndex = i + 1;
            pagerMarkup.push('<div class="pagerLink" style="width: '+ pagerElPercentW +'%;"><div class="pager'+ oneBasedIndex +'"></div></div>');
        });
        // Insert the pager elements into the markup
        pager.append(pagerMarkup.join(''));

        // Make the highlight bar the same width as each pager element
        highlightBar.css('width', pagerElPercentW+'%');

        homeSlidesContainer.cycle({
            activePagerClass: 'active',
            fx: 'scrollHorz',
            timeout: 4500,
            before: function(curr, next, opts) {
                // Slide the highlight bar to the next slide's pager anchor. Cancel any
                // unfinished animations on the highlight bar and then start a new one.
                var left    = 0.01 * pagerElPercentW * jQuery(next).index() * parseInt(jQuery(next).css('width'));
                highlightBar.stop(true).animate({ 'left': left }, 500);
            },      
            pager: '#slide-box #slide div.slideshow-progress-bar-wrap div.slideshow-progress-bar',
            pagerAnchorBuilder: function(idx, slide) {
                // Selector string to grab the pager for each slide
                return '#slide-box #slide div.slideshow-progress-bar-wrap div.slideshow-progress-bar div.pagerLink:eq(' + idx + ')';
            },
            prev: '#pre', 
            next: '#next'
        });
    }
    homePageEvents();
    $('#pages').find(':first').addClass('pre-page');
    $('#pages').find(':last').addClass('next-page');
});
